<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/5
 * Time: 15:57
 */


//支付涉及相关方法
function getsn($merchant){
    return generate_randsn();
}

function sign_rsa($keyStr16){
    $signMsg;
    $pubilc_keys = openssl_get_publickey(file_get_contents(C('__pem__').'/system_rsa_public_key.pem'));
    openssl_public_encrypt($keyStr16, $signMsg, $pubilc_keys,OPENSSL_PKCS1_PADDING); //注册生成加密信息
    return base64_encode($signMsg); //base64转码加密信息
}

function sign_verify($data,$sign){
    $pubilc_keys = openssl_get_publickey(file_get_contents(C('__pem__').'/system_rsa_public_key.pem'));
    return openssl_verify($data, base64_decode($sign), $pubilc_keys);
}

function decode_rsa($keySignStr){
    $signMsg;
    $private_keys = openssl_pkey_get_private(file_get_contents(C('__pem__').'/pkcs8_rsa_private_key_2048.pem'));
    openssl_private_decrypt(base64_decode($keySignStr), $signMsg, $private_keys); //注册生成加密信息
    return $signMsg; //base64转码加密信息
}

function sign_sha1($sign_md5){
    $signMsg;
    $private_keys = openssl_pkey_get_private(file_get_contents(C('__pem__').'/pkcs8_rsa_private_key_2048.pem'));
    openssl_sign($sign_md5, $signMsg, $private_keys,OPENSSL_ALGO_SHA1); //注册生成加密信息
    return base64_encode($signMsg); //base64转码加密信息
}

function sign_aes($aes_content, $keyStr16){
    $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
    $iv_size = mcrypt_enc_get_iv_size($cipher);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    if (mcrypt_generic_init($cipher, $keyStr16, $iv) != -1)
    {
        $cipherText = mcrypt_generic($cipher,pad2Length($aes_content,16));
        mcrypt_generic_deinit($cipher);
        mcrypt_module_close($cipher);

        // Display the result in hex.
        //printf("encrypted result:%s\n",base64_encode($cipherText));
        return base64_encode($cipherText);
    }
}

function pad2Length($text, $padlen){
    $len = strlen($text)%$padlen;
    $res = $text;
    $span = $padlen-$len;
    for($i=0; $i<$span; $i++){
        $res .= chr($span);
    }
    return $res;
}

function generate_randsn( $length = 28 ) {
    // 密码字符集，可任意添加你需要的字符
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $sn = '';
    for ( $i = 0; $i < $length; $i++ )
    {
        // 这里提供两种字符获取方式
        // 第一种是使用 substr 截取$chars中的任意一位字符；
        // 第二种是取字符数组 $chars 的任意元素
        // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
        $sn .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }
    return $sn;
}

function decode_aes($keyStr16,$aes_content){
    $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
    $iv_size = mcrypt_enc_get_iv_size($cipher);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    if (mcrypt_generic_init($cipher, $keyStr16, $iv) != -1)
    {
        $cipherText = mdecrypt_generic($cipher,base64_decode($aes_content));
        mcrypt_generic_deinit($cipher);
        mcrypt_module_close($cipher);

        // Display the result in hex.
        //printf("encrypted result:%s\n",base64_encode($cipherText));
        return $cipherText;
    }
}

function decodeUnicode($str)
{
    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
        create_function(
            '$matches',
            'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
        ),
        $str);
}

//不同环境下获取真实的IP
function get_ip(){
    //判断服务器是否允许$_SERVER
    if(isset($_SERVER)){
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }elseif(isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }else{
            $realip = $_SERVER['REMOTE_ADDR'];
        }
    }else{
        //不允许就使用getenv获取
        if(getenv("HTTP_X_FORWARDED_FOR")){
            $realip = getenv( "HTTP_X_FORWARDED_FOR");
        }elseif(getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        }else{
            $realip = getenv("REMOTE_ADDR");
        }
    }

    return $realip;
}

function isMobile() {
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset($_SERVER['HTTP_VIA'])) {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高。其中'MicroMessenger'是电脑微信
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile','MicroMessenger');
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}